package com.zxf.crypt.advice;

import com.zxf.crypt.anno.ZxfDecryptRequest;
import com.zxf.crypt.anno.ZxfEncryptResponse;
import org.springframework.core.MethodParameter;

import java.util.Objects;

/**
 * 判断是否需要进行加密
 *
 * @author zxf
 */
public class NeedCrypt {

    private NeedCrypt() {
    }

    /**
     * 判断是否需要对结果进行加密
     *
     * @param methodParameter
     * @return
     */
    public static boolean isNeedEncrypt(MethodParameter methodParameter) {
        //在类上面是否有 zxfEncryptResponse 注解
        boolean classPresent = methodParameter.getContainingClass().isAnnotationPresent(ZxfEncryptResponse.class);
        //在方法上是否有 zxfEncryptResponse 注解
        boolean methodPresent = Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(ZxfEncryptResponse.class);
        if (classPresent) {
            return true;
        }
        //当类上面没有加密注解时，就需要判断方法上有没有加密注解
        if (methodPresent) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否需要对参数进行解密
     *
     * @param methodParameter
     * @return
     */
    public static boolean isNeedDecrypt(MethodParameter methodParameter) {
        boolean classPresent = methodParameter.getContainingClass().isAnnotationPresent(ZxfDecryptRequest.class);
        boolean methodPresent = Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(ZxfDecryptRequest.class);
        // 当类上面有 DecryptRequest 注解时，表示所有的参数都是加密后的，需要对参数进行解密
        if (classPresent) {
            return true;
        }
        if (methodPresent) {
            return true;
        }
        return false;
    }
}